<?php

/**
 * RabbitCMS
 * 
 * @author TrongHM
 * @since		2.0.5
 */
class Rabbit_Model_Factory extends Tomato_Model_Dao_Factory {

    /**
     * @var Rabbit_Model_Factory
     */
    private static $_instance;
    /**
     * @var string
     */
    private $_module;
    /**
     * @var Tomato_Widget
     */
    private $_widget;

    private function __construct() {
        $config = Tomato_Config::getConfig();
        $this->_dbAdapter = str_replace(' ', '_', ucwords(str_replace('_', ' ', strtolower($config->db->adapter))));
    }

    /**
     * Override getInstance()
     * @return Rabbit_Model_Factory
     */
    public static function getInstance() {
        if (null == self::$_instance) {
            self::$_instance = new self();
        }
        /**
         * Reset
         */
        self::$_instance->reset();
        return self::$_instance;
    }

    /**
     * @param string $module Name of module
     * @return Tomato_Model_Dao_Factory
     */
    public function setModule($module) {
        $this->_module = $module;
        return $this;
    }

    /**
     * @param Tomato_Widget $widget Widget instance
     * @return Tomato_Model_Dao_Factory
     */
    public function setWidget($widget) {
        $this->_widget = $widget;
        $this->_module = $widget->getModule();
        return $this;
    }

    /**
     * Reset the module and widget
     */
    public function reset() {
        $this->_module = null;
        $this->_widget = null;
    }

    /**
     * override __call
     */
    public function __call($name, $agruments) {
        if (strlen($name) <= 8 || substr($name, 0, 3) != 'get' || substr($name, -5) != 'Model') {
            return;
        }
        $name = substr($name, 3);
        $name = substr($name, 0, -5);
        $name = ucfirst($name);
        if (null == $this->_module) {
            throw new Exception('Module is not set');
        }
        if (null == $this->_widget) {
            $class = ucfirst($this->_module) . '_Models_' . $name;
        } else {
            $class = ucfirst($this->_module) . '_Widgets_' . ucfirst(strtolower($this->_widget->getName())) . '_Models_' . $name;
        }
        $dbAdapter = Rabbit_Db_Adapter::factory()->getDbAdapter();
        $model = new $class($dbAdapter);
        //Tomato_Config::getConfig()->localization->languages->default;
        $model->setLang(Tomato_Config::getConfig()->web->language->code);
        return $model;
    }

}
